﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

namespace Ama.BugTracker.Web
{
    internal static class Extensions
    {
        /// <summary>
        /// 执行SQL并返回一个DataTable
        /// </summary>
        /// <param name="command"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        internal static DataTable ExecuteDataTableSQL(this MySqlCommand command, string sql)
        {
            if (command.Connection == null)
                throw new Exception("必须为MySqlCommand指定Connection参数！");
            if (string.IsNullOrEmpty(command.CommandText))
                command.CommandText = sql;

            try
            {
                MySqlDataAdapter adapter = new MySqlDataAdapter(command);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    return ds.Tables[0];
                }
                else
                {
                    return null;
                }
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 执行SQL并返回一行，超过一行则抛出异常，没有行则返回 null
        /// </summary>
        /// <param name="command"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        internal static DataRow ExecuteFirstRowSQL(this MySqlCommand command, string sql)
        {
            DataTable table = ExecuteDataTableSQL(command, sql);
            int count = table.Rows.Count;
            if (count >= 2)
            {
                throw new InvalidOperationException(string.Format("执行SQL“{0}”时期待返回一行，现在返回了 {1} 行",
                    sql, count));
            }
            return count > 0 ? table.Rows[0] : null;
        }

        /// <summary>
        /// 执行SQL并返回一行，没有行或超过一行则抛出异常
        /// </summary>
        /// <param name="command"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        internal static DataRow ExecuteSingleRowSQL(this MySqlCommand command, string sql)
        {
            DataTable table = ExecuteDataTableSQL(command, sql);
            int count = table.Rows.Count;
            if (count != 1)
            {
                throw new InvalidOperationException(string.Format("执行SQL“{0}”时期待返回一行，现在返回了 {1} 行",
                    sql, count));
            }
            return table.Rows[0];
        }
    }
}